package org.msn.server.handler.impl;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.msn.model.dto.ConnectDTO;
import org.msn.model.dto.SendMsgDTO;
import org.msn.model.entity.UserEntity;
import org.msn.model.rest.RestCode;
import org.msn.model.rest.RestResult;
import org.msn.mapper.database.Repository;
import org.msn.server.handler.WebSocketRequestHandler;
import org.msn.util.JsonUtil;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class DefaultWebSocketRequestHandlerImpl extends WebSocketRequestHandler {
    private static Map<Integer, ChannelHandlerContext> activeConnection = new ConcurrentHashMap<>();

    public DefaultWebSocketRequestHandlerImpl(Repository repository) {
        super(repository);
    }

    @Override
    protected void sendMsg(ChannelHandlerContext ctx, SendMsgDTO data) {
        data.setIsSelf(false);
        RestResult result = new RestResult(RestCode.successSendMsg, data);
        ctx.channel().writeAndFlush(new TextWebSocketFrame(JsonUtil.toJson(result)));

        data.setIsSelf(true);
        result.setData(data);
        String json = JsonUtil.toJson(result);

        String finalJson = json;
        activeConnection.forEach((k, v) -> {
            if (data.getFromId().equals(k)) {
                return;
            }

            v.channel().writeAndFlush(new TextWebSocketFrame(finalJson));
        });
    }

    @Override
    protected void connect(ChannelHandlerContext ctx, ConnectDTO data) {
        activeConnection.put(data.getId(), ctx);
    }

    @Override
    protected void getUserByUserId(ChannelHandlerContext ctx, Long userId) {
        UserEntity userEntity = repository.getUserByUserId(userId);

        ctx.channel().writeAndFlush(new TextWebSocketFrame(JsonUtil.toJson(userEntity)));
    }
}
